<?php

class BookAR extends CActiveRecord {
	public static function model($className=__CLASS__){
		return parent::model($className);
	}

	public function tableName()	{
		return self::tblName();
	}
	
	public static function tblName(){
		return 'ccs8_book';
	}
	
	public static function dumpInfo($bookId){
		$sql = 'select book_name,fk_category,book_size from ';
		$sql .= self::tblName();
		$sql .= ' where book_id='.$bookId;
		return DBUtil::queryRow($sql);
	}
	
	public static function del($bookId = 0,$userId = 0){
		if($bookId == 0 || $userId == 0){
			return;
		}
		$sql = 'delete from '.self::tblName().' where book_id='.$bookId.' and fk_user='.$userId.' limit 1';
		DBUtil::exec($sql);
	}
	
	public static function topNewUploadPageByCid($cid,$page){
        $sql = 'select count(*) ';
        $sql .= self::from_where(array('fk_category='.$cid));
        $sql .= ' limit 1';
        $cnt = DBUtil::queryScalar($sql);
        $page->totalrecord = $cnt;

        $sql = 'select book_id,book_name,author,book_size,ctime ';
        $sql .= self::from_where(array('fk_category='.$cid));
        $sql .= ' order by ctime desc '.$page->LimitStr();
        $page->recordlist=DBUtil::queryAll($sql);
        return $page;
	}

    public static function searchBook($bookAndAuthor,$page){
        $tmp = mysql_escape_string($bookAndAuthor);
        $sql = 'select count(*)';
        $sql .= DBUtil::buildFromSingleTbl(self::tblName());
        $sql .= "where book_name like '%$tmp%' or author like '%$tmp%' limit 1";
        $cnt = DBUtil::queryScalar($sql);
        $page->totalrecord = $cnt;

        $sql = 'select book_id,book_name,author,book_size,book_desn';
        $sql .= DBUtil::buildFromSingleTbl(self::tblName());
        $sql .= "where book_name like '%$tmp%' or author like '%$tmp%'";
        $sql .= $page->LimitStr();
        $page->recordlist=DBUtil::queryAll($sql);
        return $page;
    }

    public static function authorOtherBooks($bookId = 0,$author = ''){
        $noAuthorArr = array('','佚名','未知','不详','暂无');
        if($bookId == 0 || in_array($author,$noAuthorArr)){
            return array();
        }
        $sql = 'select book_id,book_name from ';
		$sql .= self::tblName();
        $sql .= ' where author = :author and book_id <> '.$bookId.' order by click_times desc';

        $cmd = DBUtil::cmd($sql);
        $cmd->bindParam(':author',$author,PDO::PARAM_STR);
        return $cmd->queryAll();
    }

    public static function batchGetNamesByIds($bookIdArr = array()){
        if(empty($bookIdArr)){
            return array();
        }
        $sql = 'select book_id,book_name from ';
		$sql .= self::tblName();
        $sql .= ' where book_id in ('.join(',',$bookIdArr).')';
        $data = DBUtil::queryAll($sql);
        $ret = array();
        $len = count($data);
        for($i=0;$i<$len;$i++){
            $ret[$data[$i]['book_id']] = $data[$i]['book_name'];
        }
        return $ret;
    }
    
    /**
     * Batch get author and comment_times by ids
     */
    public static function batchGetBookInfoByIds($bookIdArr = array()){
        if(empty($bookIdArr)){
            return array();
        }
        $sql = 'select book_id,author,comment_times from ';
		$sql .= self::tblName();
        $sql .= ' where book_id in ('.join(',',$bookIdArr).')';
        $data = DBUtil::queryAll($sql);
        $ret = array();
        $len = count($data);
        for($i=0;$i<$len;$i++){
            $ret[$data[$i]['book_id']] = $data[$i];
        }
        return $ret;
    }
	
	public static function downloadInfo($id = 0){
		$sql = 'select book_name,book_size,book_path from ';
		$sql .= self::tblName();
		$sql .= ' where book_id = '.$id;
		return DBUtil::queryRow($sql);
	}
	
	public static function saveBook($bookNameByUser = '',$bookInfo,$categoryId = 0,$userId = 0,$userName = 'Guest',$author = '',$bookDesn = '',$bookPic = ''){
        $bookNameByUser = $bookNameByUser == '' ? $bookInfo['origin_name'] : $bookNameByUser;
		$book = new BookAR;
		$book->book_name=$bookNameByUser;
		$book->book_size=$bookInfo['size'];
		$book->book_md5=$bookInfo['md5'];
		$book->book_path=$bookInfo['book_path'];
        $book->fk_user=$userId;
        $book->user_name=$userName;
        $book->author=$author;
        $book->book_desn=$bookDesn;
        $book->book_pic=$bookPic;
        $book->ctime=time();
        //handle category
        //如果是官方分类，就写进去分类信息，如果是用户自定义分类，fk_category就写0
        if(in_array($categoryId,Yii::app()->params['sysCategoryIds'])){
            $book->fk_category=$categoryId;
            $book->category_name=CategoryAR::getNameById($categoryId);
        }
		$book->save();
		return $book->attributes['book_id'];
	}
	
	public static function updateBook($bookId,$author,$bookDesn,$bookPic){
		$props = array();
		if($author != ''){
			$props['author']=$author;
		}
		if($bookDesn != ''){
			$props['book_desn'] = $bookDesn;
		}
		if($bookPic != ''){
			$props['book_pic'] = $bookPic;
		}
		if(empty($props)){
			return false;
		}
		$post_data = array('book_id'=>$bookId,'book_pic'=>$bookPic,'sign'=>md5($bookId.'ccs8_cn'));
		MyUtil::postData('http://www.5show5.com/book/update.php','www.5show5.com',$post_data);
		
		DBUtil::update(self::tblName(),$props,'book_id='.$bookId);
		return true;
	}
	
	public static function detail($id) {
        $sql = 'select book_id,book_name,book_size,author,book_desn,';
        $sql .= 'book_pic,book_path,ctime,fk_category,category_name ';
		$sql .= self::from_where_all(array('book_id = '.intval($id)));
		$book = DBUtil::queryRow($sql);
		if(!$book){
			return $book;
		}
		if($book['book_pic']==''){
			$book['book_pic'] = '/images/no_book_pic.jpg';
		}
		return $book;
	}
	
	public static function queryByMD5($md5){
		$sql = 'select book_id ';
		$sql .= DBUtil::buildFromSingleTbl(self::tblName());
		$sql .= 'where book_md5=:md5';
		$cmd = DBUtil::cmd($sql);
		$cmd->bindParam(":md5",$md5,PDO::PARAM_STR);
		return $cmd->queryScalar();
	}
	
	public static function prop($bookId,$prop = '') {
		$sql = 'select '.$prop.' from '.self::tblName().' where book_id = '.intval($bookId);
		return DBUtil::queryScalar($sql);
	}

    public static function increDownloadTimes($id){
		DBUtil::increProp(self::tblName(),'download_times','book_id = '.$id);
	}
	
	public static function increClickedTimes($id,$delta = 1){
		DBUtil::increProp(self::tblName(),'click_times','book_id = '.$id, $delta);
	}
	
	public static function increCommentTimes($id){
		DBUtil::increProp(self::tblName(),'comment_times','book_id = '.$id);
	}
	
	public static function topDownload($limit = 10, $condition = array()){
		return self::topBook($limit,'download_times',$condition);
	}
	
	public static function topClicked($limit = 10, $condition = array()){
		return self::topBook($limit,'click_times',$condition);
	}
	
	public static function topComment($limit = 10, $condition = array()){
		return self::topBook($limit,'comment_times',$condition);
	}
	
	public static function topNewUpload($limit = 10, $condition = array()){
		$sql = 'select book_id,book_name,author,book_size,ctime ';
		$sql .= self::from_where($condition);
		$sql .= 'order by ctime desc limit '.$limit;
		return DBUtil::queryAll($sql);
	}
	
	private static function topBook($limit = 10, $type, $condition = array()){
		$sql = 'select book_id,book_name,'.$type.' ';
		$sql .= self::from_where($condition);
		$sql .= 'order by '.$type.' desc limit '.$limit;
		return DBUtil::queryAll($sql);
	}
	
	private static function from_where($condition = array()){
		$condition[] = 'book_status=1';
		$sql = DBUtil::buildFromSingleTbl(self::tblName());
		$sql .= DBUtil::buildWhere($condition);
		return $sql;
	}

	private static function from_where_all($condition = array()){
		$sql = DBUtil::buildFromSingleTbl(self::tblName());
		$sql .= DBUtil::buildWhere($condition);
		return $sql;
	}

}
